package com.skillworld.webapp.web.pages.rest.department;

import java.util.Collections;
import java.util.List;
import java.util.Locale;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.InjectService;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.department.Department;
import com.skillworld.webapp.model.departmentservice.DepartmentService;
import com.skillworld.webapp.web.services.I18n;
import com.skillworld.webapp.web.util.DepartmentDisplayComparator;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;


@ContentType("text/xml")
public class ListDepartments
{    
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    @Property
    private List<Department> departments;
    
    @SuppressWarnings("unused")
    @Property
    private Department dept;   // loop iterator

    @Property
    private Locale locale;

    @InjectService("I18n")
    private I18n i18n;
    
    @SuppressWarnings("unused")
    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;

    @Inject
    private DepartmentService departmentService;

    @Inject
    private Request request;
   

    void onPassivate() 
    {
        return;
    }
    
    void onActivate()
    {
        if(!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
        
        String langParam = request.getParameter("lang");
        
        locale = i18n.selectLocale(langParam);
        departments = departmentService.listDepartments();
        Collections.sort(departments, new DepartmentDisplayComparator(locale));
    }
    
}
